import React, { useState, useEffect, useRef } from 'react';
import { Link, useDispatch, useSelector, history } from 'umi';
import Header from '@/components/Header/Header';
import { Picture, Message, Price } from '@/design';
import { isEmpty, getUmePic } from '@/utils/common';
import { queryProducts } from '@/services/store';
import useDebounceFn from '@/utils/useDebounceFn';
import SpecPicker from './components/specPicker';
import ShoppingCart from './components/shoppingCart';
import NumberPicker from '@/components/NumberPicker/NumberPicker';
import Empty from '@/components/Empty/Empty';
import styles from './index.less';

export default function (props: any) {

  let unmount = false;
  const cartRef = useRef();
  const dispatch = useDispatch();
  const hasMoreRef = useRef<boolean>(true);
  const pageNoRef = useRef<number>(1);
  let [ goodsDetail, setGoodsDetail] = useState({});
  let [ specVisiable, setSpecVisiable ] = useState<boolean>(false);
  const { currentstore } = useSelector((state: any) => state.currentstore);
  const { cartList } = useSelector((state: any) => state.cartList);

  const [shoppingVisiable, setShoppingVisiable] = useState<boolean>(false);
  const inputRef: any = useRef<HTMLInputElement>(null);

  const [params, setParams] = useState({
    productName: ''
  })

  useEffect(() => {
    console.log(123123)
    fetchProducts();
  }, [params])

  useEffect(() => {
    !isEmpty(inputRef) && inputRef.current.focus();
    return () => {
      unmount = true;
    }
  }, [])

  useEffect(() => {
    setShoppingVisiable(cartList.length ? true : false);
  }, [cartList.length])

  const [listDt, setListDt] = useState([])

  //加入购物车
  const addCartList = (goodDetail: any) => {
    const { productId, categoryId, productName, productIcon1, productPrice } = goodDetail;
    let good = {
      tasteList: [],
      categoryId,
      productIcon: productIcon1,
      productId,
      productName,
      productPrice,
      productQuantity: 1
    }
    let tempMap = new Map();
    let carListObj = mapCartList(cartList);
    let cartItem = carListObj[productId];
    let newCartList = JSON.parse(JSON.stringify(cartList));
    console.log('newCartListnewCartList==', newCartList)
    if (!isEmpty(cartItem)) {
      newCartList = newCartList.map((item: any) => {
        if (item.productId === productId) {
          return {
            ...item,
            productQuantity: item.productQuantity + 1
          }
        }
        return item
      })
    } else {
      newCartList.push(good)
    }
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })

  }


  /* 搜索 */
  const handleInputSearch = (event: any) => {
    setParams({
      productName: event.target.value
    })
  }


  /* 展示/隱藏規格彈窗 */
  const handleClickAdd = (_item: any) => {
    if (isEmpty(_item.tasteCategoryList)) {//单规格的時候不顯示彈框
      addCartList(_item)
    } else {
      setGoodsDetail(_item);
      setSpecVisiable(true)
    }
  }

  const { run: fetchProducts } = useDebounceFn(async (value: any) => {
    if (isEmpty(currentstore) || isEmpty(params['productName'])) return;
    let result = await queryProducts({
      ...params,
      braId: currentstore.braId,
    });
    if (unmount || !result ) return false;
    setListDt(result.data);
  }, 300)

  //將cartList的數據整合成key value productId ===> 數組
  const mapCartList = (array: any) => {
    return array.reduce((m: any, n: any) => {
      if (!m[n.productId]) {
        m[n.productId] = { list: [] }
      }
      m[n.productId].list.push(n)
      return m
    }, {})
  }

  const handleMuilSub = (productId: string) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let carListObj = mapCartList(newCartList);
    let cartItem =  carListObj[productId];
    let cartLg = cartItem.list.length; //当前这一产品在购物车总共的长度
    let lastItem = cartItem.list[cartLg - 1] ;//拿到最後一項
    let cartItemList:any =  [];
    if(lastItem.productQuantity === 1) { //等于1的时候
      cartItemList = [...cartItem.list.slice(0, cartLg - 1)]
    } else {
      lastItem = {
        ...lastItem,
        productQuantity: lastItem.productQuantity - 1
      }
      cartItemList =  [...cartItem.list.slice(0, cartLg - 1), lastItem];
    }
    carListObj[productId].list = cartItemList;
    newCartList = Object.values(carListObj).map((item:any)=>{
      return item.list
    })
    newCartList = newCartList.flat(Infinity)
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
  }

  //多規格的加和減
  const getMuliButton = (sum:number, item: any) => {
    return (<div className={`${styles.num_picker} ${props.className || ''}`}>
    <button
      type="button"
      className={styles.sub}
      onClick={() => {handleMuilSub(item.productId)}}
    >-</button>
    <input
      type="text"
      readOnly
      className={`${styles.num} ${props.hideNumber ? styles.hideNumber : ''}`}
      value={sum}
      maxLength={3}
    />
    <button
      type="button"
      className={styles.add}
      onClick={()=>{handleClickAdd(item)}}
    >+</button>
  </div>)
  }

  //渲染按鈕
  const getGoodsButton = (item: any) => {
    let newCartList = JSON.parse(JSON.stringify(cartList));
    let carListObj = mapCartList(newCartList);
    let cartItem = carListObj[item.productId];
    const { tasteCategoryList } = item;
    if (isEmpty(cartItem)) {
      return <button className={styles.add_cart} onClick={() => { handleClickAdd(item) }}></button>
    } else {

      let sum = cartItem.list.reduce((prev: any, cur: any) => {
        return prev + cur.productQuantity;
      }, 0)
      if (isEmpty(tasteCategoryList)) {//單規格的
        return <div className={styles.add_cart_icon_wrap}><NumberPicker value={sum} attr={item} onChange={handleNumChange} /></div>
      } else {
        return <div className={styles.add_cart_icon_wrap}>{getMuliButton(sum, item)}</div>
      }
    }
  }


  const handleNumChange = (num: number, curSpec: any)=> {//这边只针对单规格商品
    let carListObj = mapCartList(cartList);
    const { productId } = curSpec;
    let newCartList = JSON.parse(JSON.stringify(cartList));
    if(num === 0) {
      newCartList = newCartList.filter((item:any)=>{
        return item.productId !== productId
      })
    }
    newCartList = newCartList.map((item: any)=>{
      let cartItem =  carListObj[item.productId].list[0];
      if(productId === item.productId) {
        return {
          ...item,
          productQuantity: num,
          num
        }
      } 
      return item
    })
    dispatch({
      type: 'cartList/saveCartList',
      payload: newCartList
    })
  }

  const renderCard = (_item: any, _index: number) => {
    return (<li className={styles._item_box} key={_index} style={{ animationDelay: `${_index % 10 / 10}s` }} >
      <div className={styles.img_box}>
        <Picture className={styles.img} src={`${getUmePic(_item.productIcon1)}`} />
      </div>
      <div className={styles.info_box}>
        <h4 className={styles.title}>{_item.productName}</h4>
        <p>
          <span>月售  {_item.monthSaleAmount}</span>
          {_item.isShowStock ? <span>剩餘  {_item.stockNum}</span> : null}
        </p>
        <div className={styles.price}><Price price={_item.productPrice} /></div>
      </div>
      {/* P是套餐 S是單品 */}

      { _item.productType === 'S' ? getGoodsButton(_item) : <button className={styles.choose_btn}>選擇套餐</button>}
    </li>)
  }

  const countOccurrences = (arr: any) => arr.reduce((a:any, v:any) => (a + v.productQuantity ), 0);

  return <div className={styles.search_wrap}>
    <Header hasBack>
      <div className={styles.search_input}>
        <input ref={inputRef} type="text" placeholder="搜索商品" onChange={handleInputSearch} />
      </div>
    </Header>
    <ul className={shoppingVisiable ? styles.hasFooter : '' }>
    <SpecPicker onClose={()=>setSpecVisiable(false)} goodsDetail={goodsDetail} specVisiable={specVisiable}/> 
    {
      listDt.length > 0 ? listDt.map((item: any, index: number) => {
        return renderCard(item, index)
      }) : <Empty />
    }
     <ShoppingCart shoppingVisiable={shoppingVisiable} num={countOccurrences(cartList)} />
    </ul>
   
   
  </div>
}